import { useEffect, useState } from "react";

export default function useLocalStorage(key, def) {
    const [value, setValue] = useState(() => {
        const jsonValue = localStorage.getItem(key);
        if (jsonValue !== null) return JSON.parse(jsonValue);

        if (typeof def === "function") {
            return def();
        } else {
            return def;
        }
    })

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value))
    }, [key, value])

    return [value, setValue];
}